#include "ip.h"

IP::IP()
{
}

cv::Mat IP::qimage2mat(const QImage& qimage)
{
  cv::Mat mat = cv::Mat(qimage.height(), qimage.width(), CV_8UC4, (uchar*)qimage.bits(), qimage.bytesPerLine());
  cv::Mat mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3 );
  int from_to[] = { 0,0,  1,1,  2,2 };
  cv::mixChannels( &mat, 1, &mat2, 1, from_to, 3 );
  return mat2;
}

QImage IP::mat2qimage(const cv::Mat& image)
{
  QImage qImage(
      image.data,
      image.size().width,
      image.size().height,
      image.step,
      QImage::Format_RGB888
      );

  return qImage.rgbSwapped();
}

RGB& IP::getRGB(cv::Mat &mat, cv::Point p)
{
  return getRGB(mat, p.y, p.x);
}

RGB& IP::getRGB(cv::Mat &mat, int y, int x)
{
  //assert((mat.step/mat.cols) == sizeof(RGB));
  RGB *data = (RGB*)(mat.data  + y * mat.step + x * sizeof(RGB));
  return *data;
}

const RGB& IP::getRGB(const cv::Mat &mat, int y, int x)
{
  //assert((mat.step/mat.cols) == sizeof(RGB));
  const RGB *data = (const RGB*)(mat.data  + y * mat.step + x * sizeof(RGB));
  return *data;
}

cv::Mat IP::separateGround(cv::Mat& mat, RGB bg_color)
{
  cv::Mat ret(mat.rows, mat.cols, CV_8UC3);
  RGB white(255, 255, 255), black(0, 0, 0);
  for (int y = 0; y < mat.rows; y++)
  {
    for (int x = 0; x < mat.cols; x++)
    {
      const RGB& color = getRGB(mat, y, x);
      RGB& ret_color = getRGB(ret, y, x);
      if (color.b != bg_color.b || color.g != bg_color.g || color.r != bg_color.r)
        ret_color = color;
        //ret_color.set(white);
      else
        ret_color.set(white);
    }
  }
  return ret;
}
